//
//  PYPanControl.swift
//  ltsp
//
//  Created by jyvyi_ios on 2022/7/11.
//

import UIKit

class PYPanControl: UIControl {

    override init(frame: CGRect) {
        super.init(frame: frame)

        let pan = UIPanGestureRecognizer.init(target: self, action: #selector(btnPanEvent(_:)))
        self.addGestureRecognizer(pan)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    @objc func btnPanEvent(_ pan:UIPanGestureRecognizer){
        
        let point = pan.translation(in: self.superview)
        var originFrame = self.frame
        self.changeFrame(with: &originFrame, newPoint: point)
        self.frame = originFrame
        pan.setTranslation(.zero, in: self)
        
        switch pan.state {
        case .began:
            self.isEnabled = false
        case .changed:
            break
        default:
            self.setFinalFrame()
            break
        }
    }
    func setFinalFrame(){
        
        var frame = self.frame

        let maxWidth = self.superViewFrame().width
        let minHeight = 100.H
        let maxHeight = 600.H
        frame.origin.x = self.center.x <= maxWidth / 2.0 ? 0 : maxWidth - frame.size.width
        
        if frame.origin.y <= minHeight{
            frame.origin.y = minHeight
        }
        else if frame.maxY >= maxHeight{
            frame.origin.y = maxHeight - frame.size.height
        }
        UIView.animate(withDuration: 0.3) {
            self.frame = frame
        } completion: { isFinished in
            self.isEnabled = true
        }
    }
    func changeFrame(with originalFrame:inout CGRect,newPoint:CGPoint){
        
        let maxWidth = self.superViewFrame().width
        let maxHeight = self.superViewFrame().height
        if originalFrame.origin.x >= 0 , originalFrame.origin.x + originalFrame.size.width <= maxWidth {
            originalFrame.origin.x += newPoint.x
        }
        if originalFrame.origin.y >= 0 , originalFrame.origin.y + originalFrame.size.height <= maxHeight {
            originalFrame.origin.y += newPoint.y
        }
    }
    func superViewFrame() -> CGRect{
        
        guard let _ = self.superview else {
            return .zero
        }
        return self.superview!.frame
    }

}
